import requests
import json
import time


import hmac
import hashlib
import base64

# 从已有Token中提取固定前缀（假设前40位为前缀，需根据更多Token样本调整）
fixed_prefix = "EipOaUrHk76K93PQwcxDDXsjvM2Vl9IapS"

def generate_token(secret_key):
    # 动态部分：时间戳或随机字符串
    dynamic_part = str(int(time.time()))  # 时间戳
    # 或 dynamic_part = base64.b64encode(os.urandom(16)).decode()  # 随机字节串
    
    # 组合内容并生成HMAC签名（假设用SHA256算法）
    message = f"{fixed_prefix}{dynamic_part}"
    signature = hmac.new(
        secret_key.encode(),
        message.encode(),
        hashlib.sha256
    ).hexdigest()
    
    # 组合完整Token（格式参考已有样本）
    token = f"Bearer {fixed_prefix}{signature[:30]}"  # 截取签名长度匹配样本
    return token

# 测试（需知道secret_key，否则无法正确生成）
# secret_key = "your_system_secret"  # 需向管理员获取
# print(generate_token(secret_key))

# 接口地址
url = "https://10.238.52.6:18086/hbidsgate/rms/network/an/ont/list?pageNum=1&pageSize=500"

t = generate_token("")
# 请求头
headers = {
    "Accept": "application/json, text/plain, */*",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Authorization": 
    "Connection": "keep-alive",
    "Content-Type": "application/json",
    "Cookie": "cookieName=Admin-Token_18086; Admin-Token_18086=uac1751512094697Bf5V52blY14Uy08xV0hgIPRkEs7bCqMH; Admin-Token_18086_Expires-In=43200",
    "Host": "10.238.52.6:18086",
    "Origin": "https://10.238.52.6:18086",
    "Referer": "https://10.238.52.6:18086/",
    "Sec-Ch-Ua": "\"Not/A)Brand\";v=\"99\", \"Google Chrome\";v=\"115\", \"Chromium\";v=\"115\"",
    "Sec-Ch-Ua-Mobile": "?0",
    "Sec-Ch-Ua-Platform": "\"Linux\"",
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-origin",
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
}

# 请求参数（注意：URL中已包含pageNum和pageSize，此处仅传JSON参数）
payload = {
    "device": {
        "serviceAreaId": "31612"
    }
}

try:
    # 发送POST请求（verify=False忽略HTTPS证书验证，生产环境建议关闭）
    response = requests.post(url, headers=headers, data=json.dumps(payload), verify=False)
    
    # 检查响应状态
    if response.status_code == 200:
        # 解析JSON响应
        result = response.json()
        print("请求成功，数据如下：")
        print(json.dumps(result, ensure_ascii=False, indent=2))
    else:
        print(f"请求失败，状态码：{response.status_code}")
        print(response.text)
    
    # 延迟1秒避免频繁请求
    time.sleep(1)

except requests.exceptions.RequestException as e:
    print(f"请求异常：{e}")
except json.JSONDecodeError as e:
    print(f"JSON解析失败：{e}")
    print("响应内容：", response.text)